<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2018/7/7
 * Time: 10:50
 */

namespace YourApp\util;

use Handler\CommonOp;

class MsgEncoder {

    //返回16进制点字符串
    private function generateBodyProps($body_len,$encode_type,$isSubPackage){
        // [ 0-9 ] 0000,0011,1111,1111(3FF)(消息体长度)
        // [10-12] 0001,1100,0000,0000(1C00)(加密类型)
        // [ 13_ ] 0010,0000,0000,0000(2000)(是否有子包)
        // [14-15] 1100,0000,0000,0000(C000)(保留位)
        if($body_len>=1024){
            throw new \Exception('消息体最长1024位');
        }

        $ret=($body_len & 0x3FF) |
            (($encode_type<<10) & 0x1C00) |
            (($isSubPackage <<13) & 0x2000) |
            ((0<<14) & 0xC000);
        return bin2hex(pack('n',$ret));
    }

    //返回16进制点字符串
    private function generateMsgHeader($phone,$msg_type,$msg_body_props,$flow_id){
        $header_hex_string='';

        //消息id
        $header_hex_string.=$msg_type;

        //消息体属性
        $header_hex_string.=$msg_body_props;

        //手机号,12位
        $header_hex_string.=$phone;

        //流水号
        $header_hex_string.=bin2hex(pack('n',$flow_id));

        //消息包封装项 目前不考虑
        return $header_hex_string;
    }

    public function generateResponseBytesString($header,$body,$check_num){
        $hex_string=$header.$body.$check_num;
        if(strlen($hex_string)%2){
            CommonOp::writeLog('error',$hex_string , 'error');
        }
        $bit_string=pack('H*',$hex_string);
        $tmp=str_replace(pack('H*','7d'), pack('H*','7d01'), $bit_string);
        $tmp=str_replace(pack('H*','7e'), pack('H*','7d02'), $tmp);
        $bin_string=pack('H*','7e'. bin2hex($tmp).'7e');
        return $bin_string;
    }
    public function getResponseString($body,$set){
        extract($set);
        $msg_body_props=$this->generateBodyProps(strlen($body)/2,$encode_type,0);
        $header=$this->generateMsgHeader($phone,$msg_type,$msg_body_props,$flow_id);
        $check_sum=Common::calCheckSum($header.$body);
        return $this->generateResponseBytesString($header,$body,$check_sum);
    }

}
